package com.mysecurity.handler;

import com.alibaba.fastjson.JSON;
import com.mysecurity.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 认证失败处理器
 *
 * @author LILIBO
 * @since 2023-02-27
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    /**
     * 认证失败
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {

        response.setStatus(HttpServletResponse.SC_FORBIDDEN);//设置请求头为403 没权限

        response.setContentType("application/json;charset=utf-8");

        Result r = Result.error().message("认证失败请重新登录");
        String json = JSON.toJSONString(r);
        response.getWriter().write(json);
    }

}